<template>
  <div class="permissions-page">
    <div class="page-header">
      <h2>权限管理</h2>
      <p>管理系统中的所有权限，支持层级结构</p>
    </div>

    <div class="page-content">
      <div class="toolbar">
        <div class="left">
          <el-button type="primary" @click="handleAdd" v-if="hasPermission('system:permission:add')">
            <el-icon><Plus /></el-icon>
            新增权限
          </el-button>
          <el-button @click="handleExpandAll">
            <el-icon><Expand /></el-icon>
            展开全部
          </el-button>
          <el-button @click="handleCollapseAll">
            <el-icon><Fold /></el-icon>
            折叠全部
          </el-button>
        </div>
        <div class="right">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索权限名称或标识"
            style="width: 250px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

      <div class="permissions-tree">
        <el-tree
          ref="treeRef"
          :data="filteredPermissions"
          :props="treeProps"
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
        >
          <template #default="{ node, data }">
            <div class="permission-node">
              <div class="node-content">
                <el-icon class="node-icon" :class="getIconClass(data.type)">
                  <component :is="getIcon(data.type)" />
                </el-icon>
                <span class="node-label">{{ data.name }}</span>
                <el-tag size="small" :type="getStatusType(data.status)" class="status-tag">
                  {{ data.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </div>
              <div class="node-actions" v-if="hasPermission('system:permission:edit') || hasPermission('system:permission:delete')">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleEdit(data)"
                  v-if="hasPermission('system:permission:edit')"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click.stop="handleDelete(data)"
                  v-if="hasPermission('system:permission:delete')"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </el-tree>
      </div>
    </div>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限标识" prop="code">
          <el-input v-model="form.code" placeholder="请输入权限标识，如：system:user:add" />
        </el-form-item>
        <el-form-item label="权限类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择权限类型" style="width: 100%">
            <el-option label="菜单" value="menu" />
            <el-option label="按钮" value="button" />
            <el-option label="接口" value="api" />
          </el-select>
        </el-form-item>
        <el-form-item label="上级权限" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="permissionOptions"
            :props="treeSelectProps"
            placeholder="请选择上级权限"
            style="width: 100%"
            clearable
            check-strictly
          />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" style="width: 100%" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Expand, Fold, Search, Menu, Operation, Key } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 权限检查
const hasPermission = (permission) => {
  return userStore.hasPermission(permission)
}

// 响应式数据
const treeRef = ref()
const searchKeyword = ref('')
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)

// 表单数据
const formRef = ref()
const form = reactive({
  id: '',
  name: '',
  code: '',
  type: 'button',
  parentId: null,
  description: '',
  sort: 0,
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入权限标识', trigger: 'blur' },
    { pattern: /^[a-z]+:[a-z]+:[a-z]+$/, message: '权限标识格式：module:resource:action', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择权限类型', trigger: 'change' }
  ]
}

// 树形配置
const treeProps = {
  children: 'children',
  label: 'name'
}

const treeSelectProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 模拟权限数据
const mockPermissions = [
  {
    id: 1,
    name: '系统管理',
    code: 'system',
    type: 'menu',
    parentId: null,
    description: '系统管理模块',
    sort: 1,
    status: 1,
    children: [
      {
        id: 2,
        name: '用户管理',
        code: 'system:user',
        type: 'menu',
        parentId: 1,
        description: '用户管理功能',
        sort: 1,
        status: 1,
        children: [
          {
            id: 3,
            name: '新增用户',
            code: 'system:user:add',
            type: 'button',
            parentId: 2,
            description: '新增用户权限',
            sort: 1,
            status: 1
          },
          {
            id: 4,
            name: '编辑用户',
            code: 'system:user:edit',
            type: 'button',
            parentId: 2,
            description: '编辑用户权限',
            sort: 2,
            status: 1
          },
          {
            id: 5,
            name: '删除用户',
            code: 'system:user:delete',
            type: 'button',
            parentId: 2,
            description: '删除用户权限',
            sort: 3,
            status: 1
          }
        ]
      },
      {
        id: 6,
        name: '角色管理',
        code: 'system:role',
        type: 'menu',
        parentId: 1,
        description: '角色管理功能',
        sort: 2,
        status: 1,
        children: [
          {
            id: 7,
            name: '新增角色',
            code: 'system:role:add',
            type: 'button',
            parentId: 6,
            description: '新增角色权限',
            sort: 1,
            status: 1
          },
          {
            id: 8,
            name: '编辑角色',
            code: 'system:role:edit',
            type: 'button',
            parentId: 6,
            description: '编辑角色权限',
            sort: 2,
            status: 1
          },
          {
            id: 9,
            name: '权限分配',
            code: 'system:role:permission',
            type: 'button',
            parentId: 6,
            description: '角色权限分配',
            sort: 3,
            status: 1
          },
          {
            id: 10,
            name: '删除角色',
            code: 'system:role:delete',
            type: 'button',
            parentId: 6,
            description: '删除角色权限',
            sort: 4,
            status: 1
          }
        ]
      },
      {
        id: 11,
        name: '权限管理',
        code: 'system:permission',
        type: 'menu',
        parentId: 1,
        description: '权限管理功能',
        sort: 3,
        status: 1,
        children: [
          {
            id: 12,
            name: '新增权限',
            code: 'system:permission:add',
            type: 'button',
            parentId: 11,
            description: '新增权限',
            sort: 1,
            status: 1
          },
          {
            id: 13,
            name: '编辑权限',
            code: 'system:permission:edit',
            type: 'button',
            parentId: 11,
            description: '编辑权限',
            sort: 2,
            status: 1
          },
          {
            id: 14,
            name: '删除权限',
            code: 'system:permission:delete',
            type: 'button',
            parentId: 11,
            description: '删除权限',
            sort: 3,
            status: 1
          }
        ]
      }
    ]
  },
  {
    id: 15,
    name: '采购管理',
    code: 'purchase',
    type: 'menu',
    parentId: null,
    description: '采购管理模块',
    sort: 2,
    status: 1,
    children: [
      {
        id: 16,
        name: '采购订单',
        code: 'purchase:order',
        type: 'menu',
        parentId: 15,
        description: '采购订单管理',
        sort: 1,
        status: 1,
        children: [
          {
            id: 17,
            name: '新增订单',
            code: 'purchase:order:add',
            type: 'button',
            parentId: 16,
            description: '新增采购订单',
            sort: 1,
            status: 1
          },
          {
            id: 18,
            name: '编辑订单',
            code: 'purchase:order:edit',
            type: 'button',
            parentId: 16,
            description: '编辑采购订单',
            sort: 2,
            status: 1
          },
          {
            id: 19,
            name: '删除订单',
            code: 'purchase:order:delete',
            type: 'button',
            parentId: 16,
            description: '删除采购订单',
            sort: 3,
            status: 1
          }
        ]
      }
    ]
  }
]

const permissions = ref([...mockPermissions])

// 计算属性
const filteredPermissions = computed(() => {
  if (!searchKeyword.value) {
    return permissions.value
  }
  return filterTreeData(permissions.value, searchKeyword.value)
})

const permissionOptions = computed(() => {
  return [{ id: null, name: '顶级权限', children: permissions.value }]
})

const dialogTitle = computed(() => {
  return isEdit.value ? '编辑权限' : '新增权限'
})

// 方法
const getIcon = (type) => {
  const iconMap = {
    menu: Menu,
    button: Operation,
    api: Key
  }
  return iconMap[type] || Menu
}

const getIconClass = (type) => {
  const classMap = {
    menu: 'icon-menu',
    button: 'icon-button',
    api: 'icon-api'
  }
  return classMap[type] || 'icon-menu'
}

const getStatusType = (status) => {
  return status === 1 ? 'success' : 'danger'
}

const filterTreeData = (data, keyword) => {
  return data.filter(item => {
    const match = item.name.includes(keyword) || item.code.includes(keyword)
    if (item.children) {
      item.children = filterTreeData(item.children, keyword)
      return match || item.children.length > 0
    }
    return match
  })
}

const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value) || data.code.includes(value)
}

const handleSearch = () => {
  nextTick(() => {
    treeRef.value?.filter(searchKeyword.value)
  })
}

const handleExpandAll = () => {
  expandAll(treeRef.value.store.nodesMap, true)
}

const handleCollapseAll = () => {
  expandAll(treeRef.value.store.nodesMap, false)
}

const expandAll = (nodesMap, expand) => {
  for (const key in nodesMap) {
    nodesMap[key].expanded = expand
  }
}

const resetForm = () => {
  Object.assign(form, {
    id: '',
    name: '',
    code: '',
    type: 'button',
    parentId: null,
    description: '',
    sort: 0,
    status: 1
  })
  formRef.value?.clearValidate()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (data) => {
  isEdit.value = true
  Object.assign(form, { ...data })
  dialogVisible.value = true
}

const handleDelete = async (data) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除权限"${data.name}"吗？删除后不可恢复！`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 模拟删除
    const deleteFromTree = (tree, id) => {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].id === id) {
          tree.splice(i, 1)
          return true
        }
        if (tree[i].children && deleteFromTree(tree[i].children, id)) {
          return true
        }
      }
      return false
    }
    
    deleteFromTree(permissions.value, data.id)
    ElMessage.success('删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    // 模拟提交
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (isEdit.value) {
      // 模拟更新
      const updateInTree = (tree, updatedData) => {
        for (let i = 0; i < tree.length; i++) {
          if (tree[i].id === updatedData.id) {
            Object.assign(tree[i], updatedData)
            return true
          }
          if (tree[i].children && updateInTree(tree[i].children, updatedData)) {
            return true
          }
        }
        return false
      }
      
      updateInTree(permissions.value, { ...form })
      ElMessage.success('更新成功')
    } else {
      // 模拟新增
      const newPermission = {
        id: Date.now(),
        ...form
      }
      
      if (form.parentId) {
        const addToParent = (tree, parentId, newItem) => {
          for (let i = 0; i < tree.length; i++) {
            if (tree[i].id === parentId) {
              if (!tree[i].children) {
                tree[i].children = []
              }
              tree[i].children.push(newItem)
              return true
            }
            if (tree[i].children && addToParent(tree[i].children, parentId, newItem)) {
              return true
            }
          }
          return false
        }
        
        addToParent(permissions.value, form.parentId, newPermission)
      } else {
        permissions.value.push(newPermission)
      }
      
      ElMessage.success('新增成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}
</script>

<style lang="scss" scoped>
.permissions-page {
  padding: 20px;
  
  .page-header {
    margin-bottom: 20px;
    
    h2 {
      margin: 0 0 8px 0;
      font-size: 24px;
      font-weight: 600;
      color: $text-color-primary;
    }
    
    p {
      margin: 0;
      color: $text-color-regular;
      font-size: 14px;
    }
  }
  
  .page-content {
    background: white;
    border-radius: $border-radius-base;
    box-shadow: $box-shadow-light;
    
    .toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16px 20px;
      border-bottom: 1px solid $border-color-light;
      
      .left {
        display: flex;
        gap: 12px;
      }
      
      .right {
        display: flex;
        gap: 12px;
      }
    }
    
    .permissions-tree {
      padding: 20px;
      
      .permission-node {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        padding: 8px 0;
        
        .node-content {
          display: flex;
          align-items: center;
          gap: 8px;
          
          .node-icon {
            font-size: 16px;
            
            &.icon-menu {
              color: $primary-color;
            }
            
            &.icon-button {
              color: $success-color;
            }
            
            &.icon-api {
              color: $warning-color;
            }
          }
          
          .node-label {
            font-size: 14px;
            color: $text-color-primary;
          }
          
          .status-tag {
            margin-left: 8px;
          }
        }
        
        .node-actions {
          display: flex;
          gap: 8px;
          opacity: 0;
          transition: opacity 0.2s;
        }
        
        &:hover .node-actions {
          opacity: 1;
        }
      }
    }
  }
}

:deep(.el-tree-node__content) {
  height: auto;
  padding: 0;
  
  &:hover {
    background-color: $background-color-light;
  }
}

:deep(.el-tree-node__expand-icon) {
  padding: 6px;
}

:deep(.el-tree-node__label) {
  width: 100%;
}
</style> 